import { showSection } from './utils.js';

// 加载系统设置
export async function loadSettings() {
    try {
        const response = await fetch('/api/settings', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const settings = await response.json();
            document.getElementById('system-name').value = settings.system_name;
            document.getElementById('doc-store-path').value = settings.doc_store_path;
            document.getElementById('vector-db-path').value = settings.vector_db_path;
            document.getElementById('default-model').value = settings.default_model;
        }
    } catch (error) {
        console.error('加载系统设置错误:', error);
    }
}

// 初始化系统设置
export function initSettings() {
    loadSettings();

    // 保存设置表单提交
    document.getElementById('settings-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveSettings();
    });
}

// 保存系统设置
export async function saveSettings() {
    const settings = {
        system_name: document.getElementById('system-name').value,
        doc_store_path: document.getElementById('doc-store-path').value,
        vector_db_path: document.getElementById('vector-db-path').value,
        default_model: document.getElementById('default-model').value
    };

    try {
        const response = await fetch('/api/settings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            },
            body: JSON.stringify(settings)
        });

        if (response.ok) {
            alert('系统设置保存成功');
        } else {
            const errorData = await response.json();
            throw new Error(errorData.error || '保存设置失败');
        }
    } catch (error) {
        console.error('保存设置错误:', error);
        alert(error.message);
    }
}